package com.neusoft.mabaitspius.controller;

import com.neusoft.mabaitspius.util.GraphicHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.OutputStream;

@Controller
public class CodeController {

    @ResponseBody
    @RequestMapping("/checkVerifiCode")
    public String checkVerifiCode(String verifiCode, HttpServletRequest request )  {
        //获取session中的验证码字符串
        String code  = (String) request.getSession().getAttribute("verificode");
        if(code.equals(verifiCode)) {
            return "ok" ;
        }else {
            return "error" ;
        }
    }

    //获取验证码
    @ResponseBody
    @RequestMapping("/getVerifiCode")
    public String getVerifiCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        final int width = 200;           // 图片宽度
        final int height = 100;          // 图片高度
        final String imgType = "jpeg";   // 指定图片格式 (不是指MIME类型)
        // 获得 当前请求 对应的 会话对象(需要在输出流之前创建)
        HttpSession session = request.getSession();
        // 获得可以向客户端返回图片的输出流
        final OutputStream output = response.getOutputStream();
        // 创建验证码图片并返回图片上的字符串
        String code = GraphicHelper.create(width, height, imgType, output);

        // 存储到当前会话对象的属性中
        session.setAttribute("verificode", code);
        //返回验证码(字符串)
        return code;
    }
}
